package cn.tedu.order.service.impl;

import cn.tedu.order.entity.Order;
import cn.tedu.order.fegin.AccountClient;
import cn.tedu.order.fegin.EasyIdClient;
import cn.tedu.order.fegin.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;
    @Override
    @GlobalTransactional //使用全局事务控制
    @Transactional   //控制本地事务控制
    public void create(Order order) {
        //生成一个订单Id  这里是从id发号器获取
        String orderId = easyIdClient.nextId("order_business");
        Long id = Long.valueOf(orderId);
//        //临时生成一个随机的id 后期使用id发号器生成一个orderId 保证不会重复
//        long orderId = Math.abs(new Random().nextLong());
        order.setId(id);
        orderMapper.create(order);

        //远程调用库存 减少商品库存
        storageClient.decrease(order.getProductId(),order.getCount());

        //远程调用库存，扣减账户金额
        accountClient.decrease(order.getUserId(),order.getMoney());

    }
}
